#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<sys/un.h>
#include<stdlib.h>

#define N 64

int main(int argc, const char *argv[])
{
    int sockfd;
    struct sockaddr_un serveraddr, clientaddr;
    char buf[N];
    socklen_t len = sizeof(clientaddr);

    unlink("mysocket");

    sockfd = socket(AF_LOCAL, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        perror("fail to sockfd");
        return -1;
    }

    serveraddr.sun_family = AF_LOCAL;
    strcpy(serveraddr.sun_path, "mysocket");

    if(bind(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0)
    {
        perror("fail to bind");
        return -1;
    }

    while(1)
    {
        if(recvfrom(sockfd, buf, N, 0, (struct sockaddr*)&clientaddr, &len) < 0)
        {
            perror("fail to recvfrom");
            return -1;
        }
        if(strncmp(buf, "quit", 4) == 0)
        {
            break;
        }
        buf[strlen(buf) - 1] = '\0';
        printf("buf:%s %d %c %c %c %c\n", buf, len, 
            clientaddr.sun_path[0],
            clientaddr.sun_path[1],
            clientaddr.sun_path[2],
            clientaddr.sun_path[3]);
        strcat(buf, "++++----");
        if(sendto(sockfd, buf, N, 0, (struct sockaddr*)&clientaddr, sizeof(clientaddr)) < 0)
        {
            perror("fail to sendto");
            return -1;
        }
    }
    close(sockfd);
    return 0;
}